package com.bdqn.t350.web;

import com.bdqn.t350.anno.RequestMapping;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

//@WebServlet(value = "/", loadOnStartup = 1)
public class DispatcherServlet extends HttpServlet {

    Map<String, Method> map = new HashMap<>();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("doGet...............");
        //DispatcherServlet获取请求的路径，根据路径跳转到相应的方法执行
        String requestURI = req.getRequestURI();
        //http://localhost:8080/mvc/add
        String path = requestURI.substring(requestURI.lastIndexOf("/"));
        //"/add"
        System.out.println("path:" + path);
        //通过path去执行相对应方法，通过反射就可以实现
        //map.put("/add",com.bdqn.t350.HtlloServlet.add());
        //map.put("/delete",com.bdqn.t350.HtlloServlet.delete());
        Method method = map.get(path);
        //method 通过com.bdqn.t350.HtlloServlet.add()方法就知道该方法是com.bdqn.t350.web.HelloServlet 类性
        //通过方法获取类类型
        Class<?> targetClass = method.getDeclaringClass();
        try {
            //com.bdqn.t350.web.HelloServlet o = new com.bdqn.t350.web.HelloServlet();
            //o.add();
            Object o = targetClass.newInstance();
            Class<?>[] parameterClz = method.getParameterTypes();
            if (parameterClz.length == 0) {
                method.invoke(o);
            } else if (parameterClz.length == 1) {
                Class<?> tempClz = parameterClz[0];
                if (tempClz.getSimpleName().equals("HttpServletRequest")) {
                    method.invoke(o, req);
                }
                if (tempClz.getSimpleName().equals("HttpServletResponse")) {
                    method.invoke(o, resp);
                }
            } else if (parameterClz.length == 2) {
                Class<?> tempClz = parameterClz[0];
                if (tempClz.getSimpleName().equals("HttpServletRequest")) {
                    method.invoke(o, req, resp);
                } else if (tempClz.getSimpleName().equals("HttpServletResponse")) {
                    method.invoke(o, resp, req);
                }
            }

        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }


    }

    //map.put("/add",com.bdqn.t350.HtlloServlet.add());
    //map.put("/delete",com.bdqn.t350.HtlloServlet.delete());
    @Override
    public void init(ServletConfig config) throws ServletException {
        System.out.println("init................");
        //启动tomcat的时候我们就将web目录下所有带有RequestMapping注解的方法保存到map中
        //com.bdqn.t350.web  找到这个目录遍历这个目录下所有带有RequestMapping注解
        String rootPath = this.getClass().getResource("/").getPath();
        System.out.println("rootPath:" + rootPath);
        rootPath = rootPath + "com\\bdqn\\t350\\web\\";
        File file = new File(rootPath);
        File[] list = file.listFiles();
        for (File s : list) {
            System.out.println(s);
            //获得文件名,利用replaceAll替换.class后缀
            String className = s.getName().replaceAll(".class", "");
            //类名 com.bdqn.t350.web + s
            className = "com.bdqn.t350.web." + className;
            try {
                Class clzz = Class.forName(className);
                Method[] declaredMethods = clzz.getDeclaredMethods();
                for (Method declaredMethod : declaredMethods) {
                    System.out.println("method:" + declaredMethod);
                    //循环判断方式是否添加了@RequestMapping注解
                    if (declaredMethod.isAnnotationPresent(RequestMapping.class)) {
                        //得到该方法上添加了@RequestMapping注解的对象
                        RequestMapping declaredAnnotation = declaredMethod.getDeclaredAnnotation(RequestMapping.class);
                        //得到@RequestMapping注解对象的值value
                        //例如@RequestMapping("/hello.do")注解的value就是"/hello.do"
                        //需要将value值放到map中,方便后续使用
                        //declaredAnnotation.value()请求路径,declaredMethod请求的方法
                        //这样就能将请求路径和对应的方法保存到map中
                        map.put(declaredAnnotation.value(), declaredMethod);
                    }
                }
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            }
        }
    }
}
